package solutionfrommentor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

public class TestFileReader {

	public static void main(String[] args) throws IOException {
		File f = new File("lista.txt");

		Map<String, Integer> consumerTotalPriceMap = new TreeMap<String, Integer>();
		Map<String, Integer> productPricePerItemMap = new TreeMap<String, Integer>();
		Map<String, Integer> productCountMap = new TreeMap<String, Integer>();

		Integer totalPrice = 0;
		Integer mostExpensiveProductPrice = 0;
		String mostExpensiveProduct = null;

		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(f));
			String line;

			// incarcam lista rind cu rind
			while ((line = br.readLine()) != null) {
				String[] elRind = line.split(",");

				String consumerName = elRind[0];
				String productName = elRind[1];
				Integer price = Integer.parseInt(elRind[2]);

				// calcualte total price
				totalPrice += price;

				// set product price
				if (!productPricePerItemMap.containsKey(productName)) {
					productPricePerItemMap.put(productName, price);
				}

				// calculate most expensive product
				if (price > mostExpensiveProductPrice) {
					mostExpensiveProductPrice = price;
					mostExpensiveProduct = productName;
				}

				// calculate total price per each product
				if (consumerTotalPriceMap.containsKey(consumerName)) {
					price += consumerTotalPriceMap.get(consumerName);
				}
				consumerTotalPriceMap.put(consumerName, price);

				// calculate number of items for each product
				int productCount = 1;
				if (productCountMap.containsKey(productName)) {
					productCount += productCountMap.get(productName);
				}
				productCountMap.put(productName, productCount);
			}
		} finally {
			br.close();
		}

		System.out.println("Account Total");

		for (Map.Entry<String, Integer> entry : consumerTotalPriceMap
				.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}

		System.out.println("\nProduct Quantity");

		for (Map.Entry<String, Integer> entry : productPricePerItemMap
				.entrySet()) {
			System.out.println(entry.getKey() + " "
					+ productCountMap.get(entry.getKey()) + "x"
					+ entry.getValue());
		}

		System.out.println("\nMost expensive Product: " + mostExpensiveProduct);
		System.out.println("\nTotal:" + totalPrice);
	}

}